<?php

namespace app\admin\controller\user;

use app\admin\model\HelperApproveLog;
use app\admin\model\HelperInfo;
use app\admin\model\SystemVillage;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\common\controller\AdminController;
use app\common\enum\DefaultEnum;
use app\common\enum\StatusEnum;
use app\Request;
use think\App;
use think\response\Json;

#[ControllerAnnotation(title: 'user')]
class HelpUser extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = new \app\admin\model\User();
        $this->assign('sexStatus', DefaultEnum::getSexDesc());
        $this->assign('status', DefaultEnum::getEnableDesc());
        $this->assign('type', DefaultEnum::getUserTypeDesc());
        $this->assign('approveStatus', StatusEnum::getStatusDesc());
    }

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            if (input('selectFields')) return $this->selectList();
            list($page, $limit, $where) = $this->buildTableParams();
            $where[] = ['user_type', '=', 2];
            // 单独处理用户相关查询条件
            $userIdConditions = [];
            foreach ($where as $key => $condition) {
                if (isset($condition[0]) && $condition[0] === 'helpInfo.approve_status') {
                    if (!empty($condition[2])) {
                        // 根据审批状态筛选帮扶者信息
                        $query = HelperInfo::where('approve_status', $condition[1], $condition[2]);

                        // 如果是"未提交信息"的条件，则需要特殊处理
                        if ($condition[2] == -1) { // 假设-1表示未提交信息
                            // 查找没有帮扶者信息的用户
                            $allUserIds = self::$model::where([['user_type', '=', 2]])->column('id');
                            $userWithHelperIds = HelperInfo::column('user_id');
                            $userWithoutHelperIds = array_diff($allUserIds, $userWithHelperIds);

                            if (!empty($userWithoutHelperIds)) {
                                $userIdConditions[] = ['id', 'IN', $userWithoutHelperIds];
                            } else {
                                // 没有找到匹配用户时，添加不可能满足的条件
                                $userIdConditions[] = ['id', '=', -1];
                            }
                        } else {
                            // 正常的审批状态筛选
                            $helperInfo = $query->field('user_id')->select()->toArray();

                            if (!empty($helperInfo)) {
                                $userIds = array_column($helperInfo, 'user_id');
                                $userIdConditions[] = ['id', 'IN', $userIds];
                            } else {
                                // 没有找到匹配用户时，添加不可能满足的条件
                                $userIdConditions[] = ['id', '=', -1];
                            }
                        }
                    }
                    unset($where[$key]);
                }
            }

            // 合并用户ID条件到主查询条件中
            $where = array_merge($where, $userIdConditions);
            $count = self::$model::where($where)->count();
            $list = self::$model::with(['helpInfo'])->where($where)->page($page, $limit)->order($this->sort)->select()->toArray();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    #[NodeAnnotation(title: '详情', auth: true)]
    public function info(Request $request): Json|string
    {
        $row = self::$model::with(['helpInfo'])->find($request->param('id'));
        if ($row['helpInfo']) {
            $village = SystemVillage::find($row['helpInfo']['village_id']);
            $row['helpInfo']['village_name'] = $village['name'] ?? '';
        }
        empty($row) && $this->error('数据不存在');
        $this->assign('row', $row);
        return $this->fetch();
    }

    #[NodeAnnotation(title: '审批', auth: true)]
    public function approve(Request $request)
    {
        $id = $request->param('id');
        $user = self::$model::find($id);
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 获取帮扶者信息
        $helpInfo = HelperInfo::where('user_id', $user['id'])->find();
        if (!$helpInfo) {
            return $this->error('帮扶者信息不存在');
        }

        if ($request->isPost()) {
            $approveStatus = $request->param('approve_status');
            $approveRemark = $request->param('approve_remark', '');

            // 更新审批状态
            HelperInfo::where('id', $helpInfo['id'])->update([
                'approve_status' => $approveStatus,
                'approve_remark' => $approveRemark,
                'update_time' => time()
            ]);


            // 记录审批日志
            HelperApproveLog::create([
                'helper_id' => $helpInfo['id'],
                'status' => $approveStatus,
                'remark' => $approveRemark,
                'admin_id' => $this->adminUid,
                'create_time' => time()
            ]);

            return $this->success('审批成功');
        }

        $this->assign('user', $user);
        $this->assign('helpInfo', $helpInfo);
        return $this->fetch();
    }

}